package com.yyaccp.easybuy.security.service.token;

import com.yyaccp.easybuy.security.vo.LoginUser;
import com.yyaccp.easybuy.security.vo.Token;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.Base64UrlCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class TokenServiceJwtRedisImpl implements TokenService {
    @Autowired
    private RedisTemplate redisTemplate;

    private static final String JWT_SECRET = Base64UrlCodec.BASE64.encode("12@aH.a");
    private static final String REDIS_KEY_LOGIN_USER = "loginUserKey:";

    public Token createToken(LoginUser loginUser) {
        String uuid = UUID.randomUUID().toString();
        // 存储loginUser到redis
        redisTemplate.opsForValue().set(REDIS_KEY_LOGIN_USER + uuid, loginUser, Duration.ofMinutes(15));
        // 存储token到jwt的payload
        Map<String, Object> map = new HashMap<>();
        map.put("tokenKey", uuid);
        // 生成JWT
        String jwt = Jwts.builder().setClaims(map).signWith(SignatureAlgorithm.HS512, JWT_SECRET).compact();
        return new Token(jwt, loginUser.getUsername(), System.currentTimeMillis(), System.currentTimeMillis() + 600 * 1000);
    }

    public LoginUser getLoginUser(String token) {
        Assert.hasText(token, "token不能为空");
        token = token.replace("Bearer ", "");
        // 解析JWT的payload
        Claims claims = Jwts.parser().setSigningKey(JWT_SECRET).parseClaimsJws(token).getBody();
        String uuid = (String) claims.get("tokenKey");
        // 从redis中取出loginUser
        return (LoginUser) redisTemplate.opsForValue().get(REDIS_KEY_LOGIN_USER + uuid);
    }

    @Override
    public void deleteToken(String token) {
        redisTemplate.delete("loginUserKey:" + token);
    }
}
